package com.jmlong.controller;

import com.jmlong.domain.*;
import com.jmlong.service.CommodityService;
import com.jmlong.service.UserService;
import com.jmlong.utils.Result;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.ServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/commodity")
public class CommodityController {

    @Autowired
    CommodityService commodityService;

    @Autowired
    UserService userService;

    /**
     * 获取所有商品信息
     */
    @GetMapping("/getCommodityList")
    public Result getAllCommodity(Integer pageNum,Integer pageSize,String commodityType,String commodityName){

        log.info("商品查询信息中....");
        Result result = new Result();
        JSONArray records = null;

        if (pageNum==null){
            pageNum=1;
        }
        if (pageSize==null){
            pageSize=10;
        }

        if (commodityType!=null && !commodityType.equals("")){
            log.info("查询分类商品信息....");
            records = commodityService.getCommodityChooseType(pageNum,pageSize,commodityType);
        }else if (commodityName!=null && !commodityName.equals("")){
            log.info("搜索商品信息....");
            records = commodityService.searchCommodity(pageNum,pageSize,commodityName);
        }else{
            log.info("查询所有商品信息....");
            records = commodityService.getAllCommodity(pageNum,pageSize);
        }
        if (records.size()>0){
            log.info("查询成功！");
            result.setMsg("已为您查询商品信息!");
            result.setData(records);
        }else if (records.size()==0){
            log.info("查询成功！暂无商品信息！");
            result.setCode(230);
            result.setMsg("暂无商品信息！");
        }else{
            log.info("查询失败！");
            result.setCode(500);
            result.setMsg("商品信息查询失败！");
        }

        return result;
    }


    @PostMapping("/uploadImg")
    public Result uploadCommodityImg(ServletRequest servletRequest, MultipartHttpServletRequest files){
        Result result = new Result();
        String path = "D:\\GraduationJava\\src\\main\\resources\\static\\assest\\img\\commodityImg";
        String uuid = files.getParameter("uuid");
        if (uuid.equals("")){
            result.setCode(500);
            result.setMsg("由于未知因素，图片上传失败！");
        }

        MultiValueMap<String, MultipartFile> multiFileMap = files.getMultiFileMap();
        List<MultipartFile> filesList = multiFileMap.get("file");

        int filesLength = filesList.size();
        int filesSuccessFlag = 0;                                               //保存图片成功标志位

        for (MultipartFile file:filesList) {
            String fileName = file.getOriginalFilename();                   //获取上传的文件名称
            int suffixTemp = fileName.lastIndexOf(".");
            Date date = new Date();
            long timeSleep = date.getTime();

            try{
                String suffixName = fileName.substring(suffixTemp);                //获取文件后缀名
                if(!suffixName.equals(".jpg")){
                    if (!suffixName.equals(".jpeg")){
                        if (!suffixName.equals(".png")){
                            continue;
                        }
                    }
                }
                fileName = uuid+"_"+timeSleep+suffixName;        //生成新的文件名称
                File targetFile = new File(path);
                File saveFile = new File(targetFile, fileName);
                file.transferTo(saveFile);
                log.info("商家商品图片资源保存本地成功....");

                String img = "/img/commodityImg/"+fileName;
                CommodityImg commodityImg = new CommodityImg();
                commodityImg.setCommodityID(uuid);
                commodityImg.setImg(img);
                Integer res = commodityService.imsertCommodityImg(commodityImg);

                if (res==1){
                    filesSuccessFlag+=1;
                }else{
                    boolean delete = saveFile.delete();
                    if (delete){
                        log.info("图片资源信息同步数据库出错！本地图片资源已删除！");
                    }else{
                        log.info("图片资源信息同步数据库出错！本地图片资源删除失败！");
                    }
                }

            }catch (Exception e) {
                continue;
            }
        }

        if (filesLength==filesSuccessFlag){
            result.setMsg("图片全部上传成功！");
        }else if (filesSuccessFlag==0){
            result.setCode(500);
            result.setMsg("图片上传失败！");
        }else{
            result.setCode(521);
            result.setMsg("部分图片由于未知因素上传失败！");
        }
        return result;
    }

    /**
     * 删除商品信息
     * @param params 请求集
     */

    @PostMapping("/deleteCommodity")
    public Result deleteCommodity(@RequestBody Map params){
        log.info("删除商品信息中！");
        Result result = new Result();
        String uuid = (String) params.get("uuid");
        Integer res = commodityService.deleteCommodity(uuid);
        if (res==1){
            result.setMsg("删除商品信息成功！");
        }else{
            result.setCode(500);
            result.setMsg("删除商品信息失败！");
        }
        return  result;
    }

    /**
     * 删除商品图片
     * @param params 请求参数组
     */

    @PostMapping("/deleteImg")
    public Result deleteImg(@RequestBody Map params){
        log.info("图片资源删除中...");
        Result result = new Result();
        String path = "D:\\GraduationJava\\src\\main\\resources\\static\\assest\\img\\commodityImg";
        String fileName = (String) params.get("fileName");

        File targetFile = new File(path);
        File deleteFile = new File(targetFile, fileName);

        boolean deleteFlag = deleteFile.delete();
        if (deleteFlag){
            log.info("图片资源删除成功！");
            Integer res = commodityService.deleteImg(fileName);
            int count = 0;
            while(res!=1 && count<5){
                res = commodityService.deleteImg(fileName);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    log.info("系统休眠异常");
                }
            }
            if (res==1){
                log.info("商品图片删除同步数据库成功");
                result.setMsg("图片删除成功！");
            }else{
                log.info("商品图片删除同步数据库失败");
                result.setCode(500);
                result.setMsg("图片删除失败！");
            }
        }else{
            log.info("图片资源删除失败！");
            result.setCode(500);
            result.setMsg("图片删除失败！");
        }

        return result;
    }

    /**
     * 添加商品信息
     * @param servletRequest 请求信息
     * @param params    商品参数信息集合
     */

    @PostMapping("/addCommodity")
    public Result insertCommodity(ServletRequest servletRequest,@RequestBody Map params){
        Result result = new Result();
        log.info("商户添加商品");

        String loginName = (String) servletRequest.getAttribute("loginName");
        User user = userService.getAll(loginName);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        Date date = new Date();


        String uuid = UUID.randomUUID().toString().replace("-",""); //生成uuid编码
        String name = (String) params.get("commodityName");
        String price = (String) params.get("price");
        String describe= (String) params.get("describe");
        String commodityType = (String) params.get("commodityType");
        String count = (String) params.get("count");
        String collectionDate = simpleDateFormat.format(date);



        Commdity commdity = new Commdity();
        commdity.setCommodityID(uuid);
        commdity.setName(name);
        commdity.setPrice(price);
        commdity.setCount(count);
        commdity.setDescribe(describe);
        commdity.setMerchantID(user.getId());
        commdity.setFarmStatus(user.getStatus());
        commdity.setCommodityType(commodityType);
        commdity.setCollectionDate(collectionDate);

        Integer res = commodityService.addCommodity(commdity);

        if (res==1){
            log.info("商户添加成功");
            result.setMsg("添加商品成功！");
            HashMap map = new HashMap();
            map.put("commodityID",uuid);
            result.setData(map);
        }else {
            log.info("商户添加失败");
            result.setMsg("添加商品失败！");
        }
        return  result;
    }

    /**
     * 查询指定商家所有商品信息
     * @param servletRequest
     * @return
     */

    @GetMapping("/getMerchantCommodity")
    public Result getMerchantCommodity(ServletRequest servletRequest){
        log.info("商家查询商品信息");

        Result result = new Result();
        String loginName = (String) servletRequest.getAttribute("loginName");
        User user = userService.getAll(loginName);

        List<Commdity> commdityList = commodityService.getMerchantCommodity(user.getId());
        if (commdityList.size()==0||commdityList==null){
            log.info("商家商品信息为空！");
            result.setCode(200);
            result.setMsg("商品信息为空！");
            return result;
        }

        JSONArray records = commodityService.getMerchantCommodityImg(commdityList);

        if (records!=null&&records.size()>0){
            log.info("商品信息查询完毕");
            HashMap map = new HashMap();
            map.put("total",records.size());
            map.put("data",records);
            result.setMsg("查询商品信息成功！");
            result.setData(map);
        }else{
            log.info("商家商品信息为空！");
            result.setCode(200);
            result.setMsg("商品信息为空！");
        }

        return result;
    }

    /**
     * 获取商品信息详情
     */

    @PostMapping("/getCommodityDetail")
    public Result getCommodityDetail(@RequestBody Map params){
        Result result = new Result();
        String uuid = (String) params.get("uuid");

        JSONArray details = commodityService.getCommodityDetail(uuid);
        if (details!=null){
            result.setMsg("商品信息查询成功！");
            result.setData(details);
        }else{
            result.setCode(500);
            result.setMsg("商品信息查询失败！");
        }
        return result;

    }

    /**
     * 更新商品信息详情
     * @param params
     */

    @PostMapping("/updateCommodityDetail")
    public Result updateCommodityDetail(@RequestBody Map params){
        log.info("商品信息更新中....");
        Result result = new Result();

        String uuid = (String) params.get("uuid");
        String name = (String) params.get("commodityName");
        String price = (String) params.get("price");
        String describe = (String) params.get("describe");
        String commodityType = (String) params.get("commodityType");
        String count = (String)params.get("count");

        Integer res = commodityService.updateCommodityDetail(uuid, name, price, describe,commodityType,count);

        if (res==1){
            log.info("商品信息同步数据库成功！");
            result.setMsg("商品信息更新成功！");
        }else{
            log.info("商品信息同步数据库失败！");
            result.setCode(500);
            result.setMsg("商品信息更新失败！");

        }
        return result;
    }

    /**
     * 添加商品生长信息
     */

    @PostMapping("/addCommodityGrowUp")
    public Result addCommodityGrowup(@RequestBody Map params){
        log.info("商户添加商品生长信息中.....");
        Result result = new Result();

        Integer integer = commodityService.addCommodityGrowup(params);
        if (integer==1){
            log.info("添加成功！");
            result.setMsg("添加生长信息状况成功！");
        }else{
            log.info("添加失败！");
            result.setCode(500);
            result.setMsg("添加生长信息状况失败！");
        }

        return  result;
    }

    /**
     * 查询商品生长信息
     * @param params 请求数据集
     */
    @PostMapping("/getCommodityGrowUp")
    public Result getCommodityGrowUp(@RequestBody Map params){
        log.info("商户查询商品生长信息中.....");
        Result result = new Result();

        List<CommodityGrowUp> list = commodityService.getCommodityGrowUp(params);
        if (list.size()>0){
            log.info("查询成功！");
            result.setMsg("查询商品生长信息成功！");
            if (list.size()==1){
                result.setData(list.get(0));
            }else{
                result.setData(list);
            }

        }else if (list.size()==0){
            log.info("暂无商品生长状况信息");
            result.setCode(233);
            result.setMsg("暂无商品生长状况信息！");
        }else{
            log.info("查询失败！");
            result.setCode(500);
            result.setMsg("查询商品生长信息成功！");
        }

        return  result;
    }



    /**
     * 查询商品种类表
     */

    @GetMapping("/getCommodityType")
    public Result getCommodityType(){
        Result result = new Result();

        List<CommodityType> types = commodityService.getCommodityType();
        if (types.size()>0){
            result.setMsg("查询商品种类成功！");
            result.setData(types);
        }else if(types.size()==0){
            result.setCode(233);
            result.setMsg("暂无商品种类信息！");
        }else{
            result.setCode(500);
            result.setMsg("查询商品种类信息失败！");
        }
        return result;
    }

}
